package controller

import (
	"log"
	"writerhelper/dao"
	"writerhelper/middleware"
	"writerhelper/model"
	"writerhelper/params"
	"writerhelper/service"

	"github.com/gin-gonic/gin"
)

type Book struct{}

func (b *Book) Initialization(c *gin.RouterGroup) {
	c.Use(middleware.ParseJwt())
	{
		c.POST("createbook", b.createBook)
		c.GET("getbookinfo", b.getBookInfo)
		c.PUT("changebookinfo", b.changeBookInfo)
		c.DELETE("deletebook", b.deleteBook)

	}

}

func (b *Book) createBook(c *gin.Context) {
	var user model.User
	email := c.MustGet("email").(string)
	if err := c.Bind(&user); err != nil {
		log.Println("信息绑定出错", err)
		return

	}
	isCreate := new(dao.BookDao).CreateBook(&user, email)
	if !isCreate {
		log.Println("更新操作失败")
		c.JSON(200, gin.H{
			"code":    "to be thinkabout",
			"message": "创建书失败",
		})
	}
	c.JSON(200, gin.H{
		"code":    "200",
		"message": "创建书籍成功",
	})

}

func (b *Book) getBookInfo(c *gin.Context) {
	email := c.Query("email")
	log.Println(email)
	bookinfos := new(dao.BookDao).FindBookInfo(email)
	c.JSON(200, gin.H{
		"code":    "200",
		"message": "查询成功",
		"data":    bookinfos,
	})

}

func (b *Book) deleteBook(c *gin.Context) {
	var bookDelete model.Book
	if err := c.Bind(&bookDelete); err != nil {
		c.String(200, "获取参数有误，绑定uri有误。")
	}
	//进行数据库操作
	if err := dao.DeleteBook(bookDelete.BookName); err != nil {
		c.JSON(200, gin.H{
			"code":    "500",
			"message": "delete book produce a wrong",
			"error":   err,
		})
	}
	c.String(200, "delete success!")

}

func (b *Book) changeBookInfo(c *gin.Context) {
	var book model.Book
	var ChangeBookInfo params.ChangeBookInfo
	if err := c.ShouldBindUri(&ChangeBookInfo); err != nil {
		c.String(200, "uri参数获取错误！")
	}
	if err := c.Bind(&book); err != nil {
		c.String(200, "书籍模型绑定错误！")
	}
	//service.HandleChangeBookInfo()
	// 通过调用服务，在服务中调用数据库的操作。
	service.NewBookService().ChangeBookInfo(ChangeBookInfo, book)

}
